<template>
  <div class="purchase" ref="my_purchase">
    <div class="purchase_header">
      <div>
        <p v-if="useRoutes.query.num == 2 || useRoutes.query.num == 3">采购编码:{{ detailData.purchaseOrderNo }}</p>
      </div>
      <el-button @click="handelClickBack">返回</el-button>
    </div>
    <!--  v-if="useRoutes.query.businessState == 3 ? false : true" -->
    <div class="purchase_supply_information">
      <div class="purchase_supply_information_serch" v-if="useRoutes.query.businessState == 3 ? false : true">
        <p>供应商</p>
        <div class="purchase_supply_information_serch_select">
          <!-- <div v-if="useRoutes.query.num == 2">{{ detailData.factoryName }}</div> -->
          <div>
            <el-select v-model="forms['factoryId']" @change="handelChangeFactory">
              <el-option v-for="(item, index) in data.gcList" :key="index" :label="item.label" :value="item.value">{{
                item.label
              }}</el-option>
            </el-select>
            <el-button :class="forms['factoryId'] == null ? 'add_btn' : ''" type="primary" @click="handelClickAddSp"
              >添加商品</el-button
            >
          </div>
        </div>
      </div>
      <div class="purchase_supply_information_message">
        <div>
          <p>企业名称</p>
          <p v-if="useRoutes.query.num == 2">{{ detailData.anotherName }}</p>
          <p v-else>{{ data.informationObj?.anotherName }}</p>
        </div>
        <div>
          <p>跟单人员</p>
          <p v-if="useRoutes.query.num == 2">{{ detailData.trackerName }}</p>
          <p v-else>{{ data.informationObj?.trackerName }}</p>
        </div>
        <div>
          <p>跟单人电话</p>
          <p v-if="useRoutes.query.num == 2">{{ detailData.trackerTel }}</p>
          <p v-else>{{ data.informationObj?.trackerTel }}</p>
        </div>
        <div>
          <p>工厂地址</p>
          <p v-if="useRoutes.query.num == 2">{{ detailData.area }}{{ detailData.location }}</p>
          <p v-else>{{ data.informationObj?.area }}{{ data.informationObj?.location }}</p>
        </div>
        <div>
          <p class="info_label">是否支持开票:</p>
          <p v-if="data.informationObj.isSupportBilling == 1">
            {{ `支持开票(专票${data.informationObj.specialTicket}%)(普票${data.informationObj.ordinaryTicket}%)` }}
          </p>
          <p v-else-if="data.informationObj.isSupportBilling === 0">不支持开票</p>
        </div>
      </div>
    </div>
    <div class="purchase_commodity_information">
      <!--创建采购单列表 -->
      <p>商品信息</p>
      <el-table v-if="useRoutes.query.num == 1" :data="tabelList" class="jzt-table" border style="width: 100%">
        <el-table-column prop="name" label="商品信息" width="480">
          <template #default="scope">
            <div class="sp_message">
              <div>
                <img :src="scope.row.mainPicUrl" alt="" />
              </div>
              <div>
                <p>{{ scope.row.productName }}</p>
                <p>
                  <!-- {{
                    JSON.parse(scope.row.skuProperties).map(it => {
                      return it.specificationVal + it.specificationName;
                    })
                  }} -->
                  {{ scope.row.skuProperties }}
                </p>
                <p>{{ scope.row.skuSpecification }}</p>
                <p>SKU编码:{{ scope.row.skuCode }}</p>
                <p>ID:{{ scope.row.productId }}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="224">
          <template #default="scope">
            <!-- <el-input v-model="scope.row.remark" placeholder="请输入备注"></el-input> -->
            <RemarkEditor v-model="scope.row.remark" />
          </template>
        </el-table-column>
        <el-table-column prop="factoryRealPrice" label="供应单价" />
        <el-table-column prop="productUnit" label="数量">
          <template #default="scope">
            <el-input-number
              style="width: 75%"
              v-model="scope.row.commodityNum"
              :controls="false"
              :min="1"
              @input="handleChangeDiscountRate(scope.row)"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="partNum" label="商品件数" />
        <template v-if="!isChainTenant">
          <el-table-column label="折扣率(%)">
            <template #default="scope">
              <el-input-number
                style="width: 75%"
                v-model="scope.row.discountRate"
                :controls="false"
                :min="0"
                @input="handleChangeDiscountRate(scope.row)"
              ></el-input-number>
              <!-- :max="100" -->
            </template>
          </el-table-column>
          <el-table-column label="折扣(元)">
            <template #default="scope">
              {{ scope.row.discountAmount }}
              <!-- <el-input-number style="width: 100px" v-model="scope.row.discountAmount" :min="0" :controls="false"></el-input-number> -->
            </template>
          </el-table-column>
        </template>

        <el-table-column prop="factoryRealPrice" label="采购实付价格">
          <template #default="scope">
            <el-input-number
              :disabled="isChainTenant"
              style="width: 75%"
              :min="0"
              :step="0.1"
              :controls="false"
              v-model="scope.row.actualAmount"
              @input="handelInputActualAmount(scope.row)"
            ></el-input-number>
            <!-- :max="scope.row.factoryRealPrice * scope.row.commodityNum" -->
          </template>
        </el-table-column>
        <el-table-column prop="" label="操作">
          <template #default="scope">
            <el-popconfirm title="确定删除吗?" @confirm="handelClickDelet(scope.row)">
              <template #reference>
                <el-button link type="primary">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
        <template #empty>
          <div style="text-align: center; padding: 20px">
            <el-empty description="这里暂时什么都没有,请选择供应商添加商品吧" />
          </div>
        </template>
      </el-table>
    </div>
    <!-- 底部表单信息 -->
    <div class="purchase_form">
      <div class="purchase_form-left">
        <el-form
          ref="ruleFormRef"
          style="max-width: 100%"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
          <!-- <el-form-item label="期望到货日期" prop="">
            <el-date-picker
              v-model="ruleForm.expectedDeliveryTime"
              :disabled="useRoutes.query.num == 2"
              type="datetime"
              placeholder="请选择"
              date-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              @change="handleDateTimeChange"
              style="width: 100%"
            />
          </el-form-item> -->
          <el-form-item label="预计生产周期" prop="expectedDeliveryDays">
            <template #label>
              <div>
                <p>预计生产周期</p>
                <p class="f12" style="line-height: 16px">(请填写天数)</p>
              </div>
            </template>
            <el-input-number
              class="input-number"
              v-model="ruleForm.expectedDeliveryDays"
              placeholder="请填写天数"
              :min="0"
              :controls="false"
              style="width: 100%"
            />
            <div style="font-size: 12px; color: #86909c">预计生产周期根据付款节点关联，在对应节点配置生效后启动时间计算！</div>
          </el-form-item>
          <template v-if="!isChainTenant">
            <el-form-item label="其他费用" prop="">
              <el-input v-model="ruleForm.otherFee" placeholder="" @input="handelInputs"></el-input>
            </el-form-item>
            <el-form-item label="优惠金额" prop="">
              <el-input v-model="ruleForm.discountAmount" placeholder="" @input="handelInputsDiscountAmount"></el-input>
            </el-form-item>
          </template>

          <el-form-item
            label="本次应付金额"
            v-if="
              shoppingLists.productInformation.informationObj.typeCode == 3 ||
              (shoppingLists.productInformation.informationObj.typeCode === 0 &&
                !shoppingLists.productInformation.informationObj.collectionPlanStatus)
            "
          >
            <template #label> <span style="color: #ff3333">*</span>本次应付金额 </template>
            <el-input-number
              class="jzt-input-number"
              :min="0"
              :max="
                useRoutes.query.num == 2
                  ? detailData.payableTotalAmount
                  : data.payTotal +
                    Number(typeof ruleForm.otherFee === 'undefined' ? 0 : ruleForm.otherFee) -
                    Number(typeof ruleForm.discountAmount === 'undefined' ? 0 : ruleForm.discountAmount)
              "
              :precision="2"
              controls-position="right"
              v-model.trim="ruleForm.currentPayableAmount"
              style="width: 100%"
            ></el-input-number>
          </el-form-item>

          <el-form-item label="本次支付说明">
            <el-input v-model="ruleForm.currentPayableRemark" maxlength="200" placeholder=""></el-input>
          </el-form-item>
          <el-form-item label="收款账户选择">
            <el-select
              v-model="ruleForm.partnerAccountId"
              filterable
              :filter-method="filterZhList"
              placeholder="请输入收款账号或户号搜索"
              style="width: 100%"
            >
              <el-option
                v-for="item in zhList"
                :key="item.partnerAccountId"
                :label="
                  item.accountName
                    ? item.accountName + '：' + item.dictName + '：' + item.account
                    : item.dictName + '：' + item.account
                "
                :value="item.partnerAccountId"
              >
                <p v-if="item.accountName">{{ item.accountName + "：" + item.dictName + "：" + item.account }}</p>
                <p v-else>{{ item.dictName + "：" + item.account }}</p>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="订单说明" prop="">
            <RemarkEditor v-model="ruleForm.remark" :isEdit="useRoutes.query.num == 2 ? false : true" />
            <!-- <el-input
              :disabled="useRoutes.query.num == 2"
              :max="120"
              v-model="ruleForm.remark"
              type="textarea"
              @input="handelInputs2"
            ></el-input> -->
          </el-form-item>
          <el-form-item label="附件" prop="">
            <el-upload
              class="upload-demo"
              v-model:file-list="imgFileList"
              ref="uploadImg"
              :show-file-list="true"
              multiple
              :limit="10"
              list-type="text"
              :auto-upload="false"
              :on-change="
                (file, fileList) => {
                  handleAvatarChangeIcon(file, fileList);
                }
              "
              :on-preview="
                file => {
                  reviewFile(file);
                }
              "
            >
              <template #trigger>
                <el-button class="update_btn" :disabled="imgFileList.length >= 10">
                  <el-icon class="f24" size="20"><Plus /></el-icon>
                </el-button>
                <p>点击上传</p>
              </template>
              <template #tip>
                <p class="f12 mt10" style="color: #86909c">支持doc/docx/pdf/jpg/png，最多上传10个。</p>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item label="是否开票" prop="isBusinessInvoice">
            <div style="display: flex; justify-content: space-between; width: 100%; background: #f5f7fa; padding: 0 20px">
              <el-radio-group v-model="ruleForm.isBusinessInvoice">
                <el-radio :value="1" :disabled="isChainTenant">开票</el-radio>
                <el-radio :value="0" :class="{ 'radio-red': isChainTenant }">不开票</el-radio>
              </el-radio-group>

              <div
                v-if="data.informationObj.isSupportBilling == 0 && ruleForm.isBusinessInvoice === 1"
                style="color: #ff3333; font-size: 12px"
              >
                当前供应商不支持开票，请致电沟通后在提交采购单！
              </div>
            </div>
            <div class="warehouse_content" v-if="ruleForm.isBusinessInvoice === 1">
              <el-select v-model="ruleForm.invoiceType" placeholder="请选择开票类型" @change="invoiceTypeChange">
                <el-option label="专票" :value="1" />
                <el-option label="普票" :value="2" />
              </el-select>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="purchase_form-right">
        <div class="purchase_form-right-top">
          <div class="header">
            <p>收货仓库</p>
            <el-select
              v-if="useRoutes.query.num == 1 || useRoutes.query.num == 3"
              v-model="ruleForm['warehouseId']"
              @change="handelChangePutAway"
            >
              <el-option v-for="(item, index) in warehouseList" :key="index" :label="item.label" :value="item.value"></el-option>
            </el-select>
            <span v-else>{{ detailData.warehouseName }}</span>
          </div>
          <p>收货信息</p>
          <div>
            <p>姓名:</p>
            <p>{{ warehouseObj.manageUserName }}</p>
          </div>
          <div>
            <p>电话:</p>
            <p>{{ warehouseObj.managePhoneNo }}</p>
          </div>
          <div>
            <p>收货地址:</p>
            <p>
              {{
                Object.keys(warehouseObj).length <= 0
                  ? ""
                  : warehouseObj.provinceName + warehouseObj.cityName + warehouseObj.districtName + warehouseObj.address
              }}
            </p>
          </div>
        </div>
      </div>
    </div>
    <div class="botton_btn" :style="{ width: footerWidth + 'px' }">
      <div class="left">
        <p v-show="!isChainTenant">
          优惠金额：-¥<span>{{ useRoutes.query.num == 2 ? detailData.discountAmount : ruleForm.discountAmount }}</span>
        </p>
        <p v-show="!isChainTenant">
          其他费用：¥<span>{{ useRoutes.query.num == 2 ? detailData.otherFee : ruleForm.otherFee }}</span>
        </p>

        <p class="invoice-amount" v-if="ruleForm.isBusinessInvoice == 1 && !isChainTenant">
          税额：¥<span>{{ useRoutes.query.num == 2 ? detailData.invoiceAmount : ruleForm.feeAmount }}</span>
        </p>
        <p>
          商品总价：¥<span>{{ useRoutes.query.num == 2 ? detailData.goodsTotalAmount : data.totalPicAll }}</span>
        </p>

        <p>
          应付金额：
          <span v-if="useRoutes.query.num == 2">{{ detailData.payableTotalAmount }}</span>
          <span v-else>{{
            data.payTotal +
            Number(typeof ruleForm.otherFee === "undefined" ? 0 : ruleForm.otherFee) -
            Number(typeof ruleForm.discountAmount === "undefined" ? 0 : ruleForm.discountAmount)
          }}</span>
        </p>
        <p
          v-if="
            shoppingLists.productInformation.informationObj.typeCode == 3 ||
            (shoppingLists.productInformation.informationObj.typeCode === 0 &&
              !shoppingLists.productInformation.informationObj.collectionPlanStatus)
          "
        >
          本次应付金额：<span>¥{{ ruleForm.currentPayableAmount }}</span>
        </p>
      </div>
      <div class="right" v-if="useRoutes.query.num == 1 || useRoutes.query.num == 3">
        <el-button type="" v-if="useRoutes.query.num == 3" @click="handelClicClose">关闭</el-button>
        <el-button type="primary" plain @click="handelClickCreatePurchase(2)"> 保存 </el-button>
        <el-button type="primary" @click="handelClickCreatePurchase(1)"> 发起采购单 </el-button>
      </div>
    </div>
  </div>
</template>
<script setup>
import { reactive, ref, onMounted, watch, onUnmounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import dayjs from "dayjs";
import {
  getFactoryInfo,
  purchaseOrderId,
  getlistByTenantId,
  // getSuppliers,
  getTempProductSkuList,
  createSubmit,
  delTempProductSku,
  savePurchaseOrder,
  getProvideList,
  // closeOder
  closPurchaseOrderId,
  getShipmentDaysByProducts
} from "@/apis/procure/index";
import {
  getFolder,
  _debounce //防抖，多次频繁触发时，只执行最后一次
} from "@/utils/index";
import { shoppingList } from "@/store/index";
const shoppingLists = shoppingList();
import { ElMessage } from "element-plus";
import { roundDecimal, mathRound } from "@/utils/summation";
import RemarkEditor from "@/components/RemarkEditor";
import { getPayAccountList } from "@/apis/order/index";
// 获取商品的数据
// 组件导入
// import dialogView from '@/components/dialogView/index.vue'
const isChainTenant = JSON.parse(localStorage.getItem("userinfo"))?.isChainTenant; //判断是否是加盟商
const useRout = useRouter();
const useRoutes = useRoute();
const ruleFormRef = ref();
const ruleForm = ref({});
const rules = ref({
  name: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
    { min: 3, max: 5, message: "Length should be 3 to 5", trigger: "blur" }
  ]
});
const zhList = ref([]); //收款账户list
const forms = ref({});
const data = reactive({
  totalPicAll: 0,
  payTotal: 0,
  // 创建采购单-------
  gcList: [], //供应商列表数据
  informationObj: {},
  // 创建采购单------end
  orderId: "",
  num: 1, //1代表普通采购单，2代表定时采购单
  totalPic: 0,
  // 清除定时
  isShowClearTime: false,
  // 清除定时-------end
  code: "" //生成的code
});
// 获取dom
const my_purchase = ref();
const footerWidth = ref();

//获取支付账户列表
const zhListCopy = ref([]); //复制一份账户列表，条件筛选的时候使用
const getPayAccountListFun = () => {
  if (!data.informationObj.factoryId) return;
  getPayAccountList({
    // factoryId: data.informationObj.factoryId || forms.value["factoryId"]
    factoryId: data.informationObj.factoryId
  }).then(res => {
    if (res.code === 200) {
      zhList.value = res.data;
      zhListCopy.value = JSON.parse(JSON.stringify(res.data));
    }
  });
};

const filterZhList = val => {
  // console.log("正在筛选收款账户  accountName  account", val);
  const filterArr = zhListCopy.value.filter(item => {
    if (item.accountName?.includes(val) || item.account?.includes(val)) {
      return item;
    }
  });
  zhList.value = filterArr;
};

// 时间转换
const handleDateTimeChange = value => {
  ruleForm.value.expectedDeliveryTime = value;
  ruleForm.value.expectedDeliveryTime = dayjs(value).format("YYYY-MM-DD HH:mm:ss");
};
// 上传
const FileList = ref([]); //商品图片list
import useMultipartOssStore from "@/store/modules/multipartOssStore.js";
const ossStore = useMultipartOssStore();
// import {
//   getFolder
//   // _debounce //防抖，多次频繁触发时，只执行最后一次
// } from "@/utils/index";
import { imgsUpload } from "@/apis/products/specifications";
const uploadImg = ref();
const imgFileList = ref([]); //编辑时商品图片list
const imgIsReady = ref(true);
const handleAvatarChangeIcon = _debounce(async (file, fileList, type = "img-word") => {
  //选中文件触发的change事件
  console.log("触发文件上传==", fileList);
  let _fileList = fileList.filter(item => item.status === "ready"); //未上传成功的图片
  const flag = await fileType(type, type === "img-word" ? _fileList : [file]);
  if (!flag) {
    if (type === "img-word") {
      ElMessage({
        message: "支持扩展名：doc/docx/pdf/jpg",
        type: "error",
        offset: 60
      });
      const errorFile = _fileList.filter(
        item =>
          !(
            item.raw.type === "image/jpeg" ||
            item.raw.type === "image/png" ||
            item.raw.type === "application/msword" ||
            item.raw.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
            item.raw.type === "application/pdf"
          )
      );
      for (let item of errorFile) {
        uploadImg.value.handleRemove(item);
      }
    }
    return;
  }
  if (type === "img-word") {
    FileList.value = fileList;
    imgIsReady.value = false;
    for (let item of _fileList) {
      await customUpload(item, { file: item }, type);
    }
    imgIsReady.value = true;
  }
}, 100);
/**
 * 校验文件类型
 */
const fileType = async (type, fileList) => {
  let flag = true;
  if (type === "img") {
    for (let item of fileList) {
      if (!(item.raw.type === "image/jpeg" || item.raw.type === "image/png")) {
        flag = false;
      }
    }
  } else if (type === "img-word") {
    for (let item of fileList) {
      if (
        !(
          item.raw.type === "image/jpeg" ||
          item.raw.type === "image/png" ||
          item.raw.type === "application/msword" ||
          item.raw.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
          item.raw.type === "application/pdf"
        )
      ) {
        flag = false;
      }
    }
  }
  return flag;
};
/**
 * 上传
 */
const getFileName = name => {
  const arr = name.split(".");
  const _arr = JSON.parse(JSON.stringify(arr));
  let _name = "";
  let _suffix = "";
  if (arr.length > 2) {
    _arr.splice(_arr.length - 1, 1);
    _name = _arr.join(".");
    _suffix = arr[arr.length - 1];
  } else {
    _name = arr[0];
    _suffix = arr[1];
  }
  const folder = getFolder();
  return folder + _name + new Date().getTime() + "." + _suffix;
};
const customUpload = async (item, option, type) => {
  // 合并已上传和当前上传文件
  const objName = getFileName(option.file.name);
  await ossStore
    .submit(objName, option.file.raw)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("文件上传成功，地址为===", res.fileUrl.split("?")[0]);
      if (type === "img-word") {
        item["fileUrl"] = res.fileUrl.split("?")[0];
      }
      item["folder"] = objName;

      const Option = JSON.parse(JSON.stringify(option));
      uploadIMG(Option); //图片上传到业务端
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};

//将图片上传到业务端服务
const uploadIMG = option => {
  const nameArr = option.file.name.split(".");
  const uploadArr = [
    {
      fileId: option.file.uid,
      objectName: option.file.folder, //目录＋文件名称
      url: option.file.img || option.file.video,
      access: "public-read",
      fileName: option.file.name, //文件名称
      bucketName: "51-jzt-dev",
      size: option.file.size,
      type: true,
      suffix: nameArr[nameArr.length - 1]
    }
  ];
  imgsUpload(uploadArr).then(res => {
    console.log(909090, res);
  });
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};
// 修改折扣率
const picData = ref(0);
const handleChangeDiscountRate = item => {
  console.log(item);
  setTimeout(() => {
    copyTabelList.value.map(it => {
      if (it.collectId === item.collectId) {
        picData.value = it.factoryRealPrice;
      }
    });
    let total = Number(item.commodityNum) * Number(item.factoryRealPrice) * (Number(item.discountRate) / 100); //实际价格
    let zkTotal =
      Number(item.commodityNum) * Number(item.factoryRealPrice) -
      Number(item.commodityNum) * Number(item.factoryRealPrice) * (Number(item.discountRate) / 100); //则扣总价
    console.log(total, zkTotal, Number(item.discountRate) / 100);
    const ddiscountAmount = roundDecimal(zkTotal / Number(item.commodityNum), 2);
    item.discountAmount = ddiscountAmount;
    item.actualAmount = roundDecimal(total, 2);
  });
};
const handelInputActualAmount = item => {
  setTimeout(() => {
    item.discountRate = mathRound((item.actualAmount / item.commodityNum / item.factoryRealPrice) * 100);
    let zkTotal =
      Number(item.commodityNum) * Number(item.factoryRealPrice) -
      Number(item.commodityNum) * Number(item.factoryRealPrice) * (Number(item.discountRate) / 100); //则扣总价
    const ddiscountAmount = roundDecimal(zkTotal / Number(item.commodityNum), 2);
    item.discountAmount = ddiscountAmount;
    // getpayTotal();
  }, 0);
};
/**
 * 上传
 */
/**
 * 获取视频时间长度
 */
// 关闭订单
const handelClicClose = () => {
  closPurchaseOrderId(useRoutes.query.purchaseOrderId).then(res => {
    console.log(res);
    if (res.code === 200) {
      ElMessage({
        type: "success",
        message: "关闭采购单成功"
      });
      setTimeout(() => {
        useRout.push({
          path: "/procure/purchase-order"
        });
      }, 1000);
    }
  });
};
// 返回
const handelClickBack = () => {
  useRout.push({
    path: "/procure/purchase-order"
  });
};
// 新创建采购单----------
const getProvideLists = async () => {
  const resalt = await getProvideList({ status: 1 }, 1000, 1);
  let arr = [];
  resalt.data.list.map(it => {
    arr.push({ label: it.anotherName, value: it.factoryId });
  });
  data.gcList = arr;
};
const handelClickAddSp = () => {
  ruleForm.value.warehouseId = "";
  warehouseObj.value = {};
  if (Object.keys(data.informationObj).length === 0) {
    ElMessage({
      type: "warning",
      message: "请先选择供应商信息"
    });
    return;
  }
  // 赋值code值
  if (data.code == undefined) {
    data.code = Date.now();
  }
  useRout.push({
    path: "/procure/purchase-order/merchant-add",
    query: {
      factoryId: data.informationObj.factoryId,
      code: data.code,
      num: useRoutes.query.num,
      purchaseOrderId: useRoutes.query.purchaseOrderId
    }
  });
};
const handelChangeFactory = v => {
  tabelList.value = [];
  // 保存缓存
  shoppingLists.productInformation.forms = forms.value;
  data.code = Date.now();
  getFactoryInfo(v).then(res => {
    console.log(res);
    // 保存缓存
    shoppingLists.productInformation.informationObj = res.data;
    data.informationObj = res.data;
    console.log(data.informationObj,9999);
    if (isChainTenant) {
      ruleForm.value.isBusinessInvoice = 0;
    } else {
      ruleForm.value.isBusinessInvoice = data.informationObj.isSupportBilling;
    }
    getPayAccountListFun();
  });
};
const warehouseList = ref([]);
const warehouseArry = ref([]);
const warehouseObj = ref({}); //获取最后的收货数据
const getlistByTenantIds = () => {
  getlistByTenantId().then(res => {
    let arr = [];
    warehouseArry.value = res.data;
    res.data.map(it => {
      arr.push({ label: it.warehouseName, value: it.warehouseId });
    });
    warehouseList.value = arr;
    // console.log("仓库list11111===", arr);
  });
};
const handelChangePutAway = v => {
  warehouseArry.value.map(it => {
    if (v === it.warehouseId) {
      warehouseObj.value = it;
    }
  });
  console.log(warehouseObj.value, "--------");
  // 存储数据
  // shoppingLists.productInformation.warehouseObj = warehouseObj.value;
};
// 新建采购单添加到缓存的数据
const tabelList = ref([]);
const copyTabelList = ref();
const getTempProductSkuLists = async () => {
  await getTempProductSkuList({ code: data.code, businessId: JSON.parse(localStorage.getItem("userinfo")).tenantId })
    .then(res => {
      // 添加字段  则扣金额，则扣率
      res.data.map(it => {
        it.discountAmount = 0; //则扣金额
        it.discountRate = 100; //则扣率
        it.commodityNum = 1; //订单商品数量
        it.actualAmount = it.factoryRealPrice * it.commodityNum; //实付金额
        if (it.partNum == null) {
          it.partNum = 1;
        }
      });
      let copyDate = JSON.stringify(res.data);
      copyTabelList.value = JSON.parse(copyDate);
      tabelList.value = res.data;
    })
    .catch(err => {
      console.log(err);
    });
};
// 删除
const handelClickDelet = item => {
  console.log(item);
  delTempProductSku({ code: data.code, skuId: item.skuId })
    .then(() => {
      ElMessage({
        type: "success",
        message: "删除成功"
      });
      getTempProductSkuLists();
    })
    .catch(err => {
      console.log(err);
    });
};
// 发起采购订单
const handelClickCreatePurchase = n => {
  const arrFiles = [];
  // 处理上传文件
  imgFileList.value.map(it => {
    arrFiles.push(it.fileUrl);
  });
  const { provinceId, cityId, districtId } = warehouseObj.value;
  const obj = JSON.stringify(warehouseObj.value);
  let warehouseObjCopy = JSON.parse(obj);
  delete warehouseObjCopy.remark;
  // tabelList.value
  let tabelListCopy = JSON.stringify(tabelList.value);
  let tabelListCopys = JSON.parse(tabelListCopy);
  let spArr = []; //商品信息
  tabelListCopys.map(it => {
    spArr.push({
      productAliasName: it.productName,
      businessSkuId: it.businessSkuId,
      collectId: it.collectId,
      mainPicUrl: it.mainPicUrl,
      commodityNum: it.commodityNum,
      partNum: it.partNum,
      remark: it.remark,
      discountRate: it.discountRate,
      discountAmount: it.discountAmount,
      currentPayableAmount: it.currentPayableAmount,
      unitPrice: it.factoryRealPrice,
      actualAmount: it.actualAmount
    });
  });
  const {
    expectedDeliveryTime,
    remark,
    otherFee,
    discountAmount,
    currentPayableAmount,
    currentPayableRemark,
    partnerAccountId,
    expectedDeliveryDays,
    originExpectedDays,
    isBusinessInvoice,
    invoiceType
  } = ruleForm.value;

  if (
    JSON.stringify(currentPayableAmount) === "" ||
    JSON.stringify(currentPayableAmount) === "null" ||
    JSON.stringify(currentPayableAmount) === undefined
  ) {
    return ElMessage({
      message: "请输入本次应付金额",
      type: "error"
    });
  }
  //获取选择的收款账户
  const selectedZhObj = zhList.value.find(item => item.partnerAccountId === partnerAccountId);
  const _selectedZhObj = {
    payAccountId: selectedZhObj?.partnerAccountId || "",
    payAccount: selectedZhObj?.account || "",
    payDictName: selectedZhObj?.dictName || "",
    payAccountName: selectedZhObj?.accountName || ""
  };
  console.log("选中的收款账户===", selectedZhObj);

  let parms = {
    purchaseOrderId: useRoutes.query.num == 3 ? useRoutes.query.purchaseOrderId : "", //采购单ID
    factoryId: data.informationObj.factoryId, //工厂id
    // attachmentFileUrls: attachmentFileUrls.value.join(","), //附件
    // expectedDeliveryTime: expectedDeliveryTime, //期望到货时间
    expectedDeliveryDays,
    originExpectedDays,
    isBusinessInvoice,
    invoiceType,
    remark: remark,
    otherFee: Number(otherFee),
    discountAmount: Number(discountAmount),
    currentPayableAmount: Number(currentPayableAmount), //本次应付金额
    currentPayableRemark: currentPayableRemark, //本次支付说明
    ..._selectedZhObj, //选中的收款账户
    // payInfoId:0,
    receivingWarehouseId: warehouseObj.value.warehouseId, //收货仓库id
    receivingName: warehouseObj.value.manageUserName, //收货信息名称
    receivingMobile: warehouseObj.value.managePhoneNo,
    receivingAreaIds: provinceId + "," + cityId + "," + districtId,
    receivingAreaDetail: warehouseObj.value.provinceName + warehouseObj.value.cityName + warehouseObj.value.districtName,
    receivingAddress: warehouseObj.value.address,
    purchaseOrderDetails: spArr,
    attachmentFileUrls: arrFiles.join(",")
  };
  // console.log("发起采购-参数===", parms);
  // return;
  if (n == 1) {
    createSubmit(parms).then(res => {
      if (res.code === 200) {
        ElMessage({
          type: "success",
          message: "创建采购单成功"
        });
        setTimeout(() => {
          useRout.push({
            path: "/procure/purchase-order"
          });
        }, 1000);
      }
    });
  } else if (n == 2) {
    savePurchaseOrder(parms)
      .then(res => {
        if (res.code === 200) {
          ElMessage({
            type: "success",
            message: "保存采购单成功"
          });
          setTimeout(() => {
            useRout.push({
              path: "/procure/purchase-order"
            });
          }, 1000);
        }
      })
      .catch(err => {
        console.log(err);
      });
  }
};
const handelInputs = () => {
  ruleForm.value.otherFee = ruleForm.value.otherFee.replace(/[^0-9.]/g, "").replace(/(\..*)\./g, "$1");
};
const handelInputsDiscountAmount = () => {
  ruleForm.value.discountAmount = ruleForm.value.discountAmount.replace(/[^0-9.]/g, "").replace(/(\..*)\./g, "$1");
};
// 新创建采购单----------end
// 查询详情---------
const detailData = ref({});
const getDetails = async () => {
  await purchaseOrderId(useRoutes.query.purchaseOrderId).then(res => {
    detailData.value = res.data;
    // 编辑时回显工产id
    forms.value.factoryId = res.data.factoryId;
    if (res.data.factoryId !== null || useRoutes.query.num == 3 || useRoutes.query.num == 2) {
      console.log(res.data, "receivingWarehouseId");
      // 在编辑的时候
      handelChangeFactory(res.data.factoryId);
      ruleForm.value = {
        discountAmount: res.data.discountAmount,
        otherFee: res.data.otherFee,
        remark: res.data.remark,
        warehouseId: res.data.receivingWarehouseId,
        expectedDeliveryTime: res.data.expectedDeliveryTime
      };
      tabelList.value = res.data.productDetailList;
      handelChangePutAway(res.data.receivingWarehouseId);
    }
  });
};

// 获取预计生产周期
const getShipmentDaysByProductsApi = async () => {
  if (tabelList.value.length == 0) {
    return;
  }
  let businessSkuIds = [];
  tabelList.value?.map(item => {
    businessSkuIds.push(item.businessSkuId);
  });
  await getShipmentDaysByProducts({
    factoryId: shoppingLists.productInformation.informationObj.factoryId,
    businessSkuIds
  }).then(res => {
    ruleForm.value.expectedDeliveryDays = res.data.maxProduceDays;
    ruleForm.value.originExpectedDays = res.data.maxProduceDays;
    console.log(res);
  });
};

// 查询详情---------end
onMounted(async () => {
  getProvideLists();
  getlistByTenantIds();
  if (isChainTenant) {
    ruleForm.value.isBusinessInvoice = 0;
  }
  if (data.code == "") {
    data.code = useRoutes.query.code;
  }
  if (useRoutes.query.num == 1 && useRoutes.query.code !== undefined) {
    await getTempProductSkuLists();
    // 新建采购单回显数据
    ruleForm.value = shoppingLists.productInformation.ruleForm;
    ruleForm.value.warehouseId = "";
    ruleForm.value.currentPayableAmount = "";
    forms.value = shoppingLists.productInformation.forms;

    await getShipmentDaysByProductsApi();
    if (isChainTenant) {
      ruleForm.value.isBusinessInvoice = 0;
    } else {
      ruleForm.value.isBusinessInvoice = shoppingLists.productInformation.informationObj.isSupportBilling;
    }
    // warehouseList.value = shoppingLists.productInformation.warehouseList;
    warehouseObj.value = shoppingLists.productInformation.warehouseObj;
    data.informationObj = shoppingLists.productInformation.informationObj;
    // console.log(888, data.informationObj);
    getPayAccountListFun(); //获取收款账户信息list
  }
  //  走详情页面
  if (useRoutes.query.num == 2 || useRoutes.query.num == 3) {
    await getDetails();
    // console.log(999, data.informationObj);
    getPayAccountListFun(); //获取收款账户信息list
  }

  // 获取dom元素给底部操作栏设置动态宽度
  if (my_purchase.value) {
    const resizeObserver = new ResizeObserver(entries => {
      for (let entry of entries) {
        footerWidth.value = entry.contentRect.width;
      }
    });

    resizeObserver.observe(my_purchase.value);
    // 组件卸载时取消监听
    onUnmounted(() => {
      resizeObserver.disconnect();
    });
  }
});

// 开票类型变化-算开票金额和税额
const invoiceTypeChange = () => {
  let num = 0;
  // 支持开票-取开票的税率，不支持取0
  if (data.informationObj.isSupportBilling == 1) {
    if (ruleForm.value.invoiceType == 1) {
      num = Number(data.informationObj.specialTicket || 0);
    } else if (ruleForm.value.invoiceType == 2) {
      num = Number(data.informationObj.ordinaryTicket || 0);
    }
  }
  let commodityPrice =
    data.payTotal +
    Number(typeof ruleForm.value.otherFee === "undefined" ? 0 : ruleForm.value.otherFee) -
    Number(typeof ruleForm.value.discountAmount === "undefined" ? 0 : ruleForm.value.discountAmount);
  // 小数点2位 *1000 避免长度失真
  ruleForm.value.feeAmount = (((commodityPrice * 1000) / 100) * num * 1000) / 1000000;
};

// 监听数据则到总价
watch(
  () => tabelList.value,
  list => {
    const realt = list.reduce((accumulator, currentObject) => {
      return accumulator + Number(currentObject.factoryRealPrice * currentObject.commodityNum);
    }, 0);
    const realt1 = list.reduce((accumulator, currentObject) => {
      return accumulator + Number(currentObject.actualAmount);
    }, 0);
    console.log(realt);
    data.totalPicAll = realt;
    data.payTotal = realt1;

    invoiceTypeChange();
  },
  {
    deep: true,
    immediate: true
  }
);
</script>
<style scoped lang="scss">
@import "./index.scss";
:deep(.radio-red) {
  .el-radio__input.is-checked + .el-radio__label {
    color: red;
  }
}
</style>
